﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightAnimation
{
    public class RotationAnimation : TransformAnimation<RotateTransform>
    {

        private double _angle;

        public double Angle
        {
            get { return _angle; }
            set { _angle = value; }
        }

        public RotationAnimation(FrameworkElement element, double angle, int seconds)
            : base(element, new TimeSpan(0, 0, seconds))
        {
            this.Angle = angle;
        }

        protected override Storyboard CreateStoryboard()
        {
            int index = PrepareElement(Element);
            var propertyPath = new PropertyPath(String.Format("(UIElement.RenderTransform).(TransformGroup.Children)[{0}].(RotateTransform.Angle)", index));
            var storyboard = new Storyboard();
            var animation = new DoubleAnimationUsingKeyFrames();
            animation.KeyFrames.Add(new EasingDoubleKeyFrame()
            {
                Value = Angle,
                KeyTime = AnimationDuration
            });
            Storyboard.SetTarget(animation, Element);
            Storyboard.SetTargetProperty(animation, propertyPath);
            storyboard.Children.Add(animation);
            return storyboard;
        }
        protected override void ApplyValues(Storyboard storyboard)
        {
            if (storyboard == null)
                throw new ArgumentNullException("storyboard");

            var animation = storyboard.Children[0] as DoubleAnimationUsingKeyFrames;
            animation.KeyFrames[0].Value = Angle;
            animation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(AnimationDuration);
        }
        public static void AnimateRotation(FrameworkElement element, double angle, int seconds)
        {
            new RotationAnimation(element, angle, seconds).Apply();
        }
    }
}
